/**
 * 数据源管理API服务层
 * 集成requestGuard防重复请求机制，遵循现有API服务模式
 */

import api from './api';
import { requestGuard, withRequestGuard } from '../utils/requestGuard';
import { notifySuccess, notifyError } from '../utils/notification';
import type {
  DataSource,
  DataSourceCreate,
  DataSourceUpdate,
  DataSourceListResponse,
  DataSourceQueryParams,
  ConnectionTestRequest,
  ConnectionTestResponse,
  BatchTestRequest,
  BatchTestResponse,
  BatchOperationRequest,
  DataSourceStats,
  TestLog,
  ApiResponse,
  ApiError
} from '../types/datasource';

/**
 * 数据源API服务类
 */
class DataSourceApiService {
  private readonly baseUrl = '/v1/datasources';

  /**
   * 获取数据源列表
   */
  getDatasources = withRequestGuard(
    'getDatasources',
    async (params: DataSourceQueryParams = {}): Promise<DataSourceListResponse> => {
      try {
        const response = await api.get<ApiResponse<DataSourceListResponse>>(this.baseUrl, {
          params: {
            page: params.page || 1,
            page_size: params.page_size || 10,
            search: params.search || undefined,
            db_type: params.db_type || undefined,
            is_active: params.is_active,
            test_status: params.test_status || undefined
          }
        });

        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '获取数据源列表失败');
        throw error;
      }
    }
  );

  /**
   * 获取数据源详情
   */
  getDatasource = withRequestGuard(
    'getDatasource',
    async (id: number): Promise<DataSource> => {
      try {
        const response = await api.get<ApiResponse<DataSource>>(`${this.baseUrl}/${id}`);
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '获取数据源详情失败');
        throw error;
      }
    }
  );

  /**
   * 创建数据源
   */
  createDatasource = withRequestGuard(
    'createDatasource',
    async (data: DataSourceCreate): Promise<DataSource> => {
      try {
        const response = await api.post<ApiResponse<DataSource>>(this.baseUrl, data);
        notifySuccess('数据源创建成功');
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '创建数据源失败');
        throw error;
      }
    }
  );

  /**
   * 更新数据源
   */
  updateDatasource = withRequestGuard(
    'updateDatasource',
    async (id: number, data: DataSourceUpdate): Promise<DataSource> => {
      try {
        const response = await api.put<ApiResponse<DataSource>>(`${this.baseUrl}/${id}`, data);
        notifySuccess('数据源更新成功');
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '更新数据源失败');
        throw error;
      }
    }
  );

  /**
   * 删除数据源
   */
  deleteDatasource = withRequestGuard(
    'deleteDatasource',
    async (id: number): Promise<void> => {
      try {
        await api.delete<ApiResponse<any>>(`${this.baseUrl}/${id}`);
        notifySuccess('数据源删除成功');
      } catch (error: any) {
        this.handleApiError(error, '删除数据源失败');
        throw error;
      }
    }
  );

  /**
   * 测试连接参数
   */
  testConnectionParams = withRequestGuard(
    'testConnectionParams',
    async (params: ConnectionTestRequest): Promise<ConnectionTestResponse> => {
      try {
        const response = await api.post<ApiResponse<ConnectionTestResponse>>(
          `${this.baseUrl}/test`,
          params
        );
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '连接测试失败');
        throw error;
      }
    }
  );

  /**
   * 测试数据源连接
   */
  testDatasourceConnection = withRequestGuard(
    'testDatasourceConnection',
    async (id: number): Promise<ConnectionTestResponse> => {
      try {
        const response = await api.post<ApiResponse<ConnectionTestResponse>>(
          `${this.baseUrl}/${id}/test`
        );
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '数据源连接测试失败');
        throw error;
      }
    }
  );

  /**
   * 批量测试数据源连接
   */
  batchTestDatasources = withRequestGuard(
    'batchTestDatasources',
    async (request: BatchTestRequest): Promise<BatchTestResponse> => {
      try {
        const response = await api.post<ApiResponse<BatchTestResponse>>(
          `${this.baseUrl}/batch-test`,
          request
        );
        const result = response.data.data;
        notifySuccess(`批量测试完成：成功 ${result.success_count} 个，失败 ${result.failed_count} 个`);
        return result;
      } catch (error: any) {
        this.handleApiError(error, '批量测试失败');
        throw error;
      }
    }
  );

  /**
   * 批量删除数据源
   */
  batchDeleteDatasources = withRequestGuard(
    'batchDeleteDatasources',
    async (datasourceIds: number[]): Promise<any> => {
      try {
        const request: BatchOperationRequest = {
          datasource_ids: datasourceIds,
          operation: 'delete'
        };
        const response = await api.post<ApiResponse<any>>(
          `${this.baseUrl}/batch-delete`,
          request
        );
        notifySuccess(`批量删除完成：删除了 ${datasourceIds.length} 个数据源`);
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '批量删除失败');
        throw error;
      }
    }
  );

  /**
   * 批量启用/禁用数据源
   */
  batchToggleDatasources = withRequestGuard(
    'batchToggleDatasources',
    async (datasourceIds: number[], enable: boolean): Promise<any> => {
      try {
        const request: BatchOperationRequest = {
          datasource_ids: datasourceIds,
          operation: enable ? 'enable' : 'disable'
        };
        const response = await api.post<ApiResponse<any>>(
          `${this.baseUrl}/batch-toggle`,
          request
        );
        const action = enable ? '启用' : '禁用';
        notifySuccess(`批量${action}完成：${action}了 ${datasourceIds.length} 个数据源`);
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, `批量${enable ? '启用' : '禁用'}失败`);
        throw error;
      }
    }
  );

  /**
   * 获取数据源统计信息
   */
  getDatasourceStats = withRequestGuard(
    'getDatasourceStats',
    async (): Promise<DataSourceStats> => {
      try {
        const response = await api.get<ApiResponse<DataSourceStats>>(`${this.baseUrl}/stats`);
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '获取统计信息失败');
        throw error;
      }
    }
  );

  /**
   * 获取数据源测试日志
   */
  getDatasourceTestLogs = withRequestGuard(
    'getDatasourceTestLogs',
    async (id: number, page: number = 1, pageSize: number = 10): Promise<{
      logs: TestLog[];
      total: number;
      page: number;
      page_size: number;
      total_pages: number;
    }> => {
      try {
        const response = await api.get<ApiResponse<any>>(
          `${this.baseUrl}/${id}/test-logs`,
          {
            params: { page, page_size: pageSize }
          }
        );
        return response.data.data;
      } catch (error: any) {
        this.handleApiError(error, '获取测试日志失败');
        throw error;
      }
    }
  );



  /**
   * 处理API错误
   */
  private handleApiError(error: any, defaultMessage: string): void {
    let errorMessage = defaultMessage;
    let errorDetails = '';

    if (error.response?.data) {
      const data = error.response.data;
      
      // 处理422验证错误
      if (error.response.status === 422) {
        if (data.detail) {
          if (Array.isArray(data.detail)) {
            errorDetails = data.detail.map((err: any) => {
              const field = err.loc ? err.loc[err.loc.length - 1] : '未知字段';
              const message = err.msg || err.message || '验证失败';
              return `${field}: ${message}`;
            }).join('\n');
            errorMessage = '表单验证失败';
          } else if (typeof data.detail === 'string') {
            errorDetails = data.detail;
          }
        }
      } else {
        errorMessage = data.message || data.detail || defaultMessage;
      }
    } else if (error.message) {
      errorMessage = error.message;
    }

    // 显示错误消息
    if (errorDetails) {
      message.error({
        content: `${errorMessage}\n${errorDetails}`,
        duration: 5
      });
    } else {
      message.error(errorMessage);
    }

    console.error('API Error:', error);
  }

  /**
   * 清除请求防护状态
   */
  clearRequestGuards(): void {
    requestGuard.clearAll();
  }

  /**
   * 获取请求防护状态
   */
  getRequestGuardStatus(): Record<string, any> {
    return requestGuard.getGuardStatus();
  }
}

// 创建并导出服务实例
export const datasourceApi = new DataSourceApiService();

// 导出类型和常量
export type { DataSourceApiService };
export default datasourceApi;
